<template>
  <view class="snap-container">
    <view class="equi-id" :style="{height:activeTab == 0 ? '178rpx' : '514rpx'}">
      <view class="tabs-top">
        <view class="tabs">
          <view class="tabs-item" @click="activeTab = index" :class="{'activeTab':activeTab == index}" v-for="(item,index) in tabsList" :key="index">
            {{item}}
          </view>
        </view>
        <view class="id">
		<picker mode="selector" :range="equipmentList" range-key="equipmentCode" @change="handerChangeEqu">
		  <text>{{equipmentCode}}</text>
		  <uni-icons type="bottom" size="12" style="margin-left: 8rpx;"></uni-icons>
		</picker>
          
        </view>
      </view>
      <view class="filter" v-if="activeTab == 0">
        <view class="filter-item">
          <picker mode="date" :value="date" @change="bindDateChange">
            <text>监测日期</text>
            <uni-icons type="bottom" size="12" style="margin-left: 8rpx;"></uni-icons>
          </picker>
        </view>
        <view class="filter-item">
          <picker mode="selector" :range="presetList" range-key="pointName" @change="handerChangeSC">
            <text>收藏点</text>
            <uni-icons type="bottom" size="12" style="margin-left: 8rpx;"></uni-icons>
          </picker>
        </view>
      </view>
      <view class="video" v-if="activeTab == 1" style="display:flex;width:100%;height:400rpx;position:relative;overflow:hidden;">
        <video v-if="isVideo" style="width: 100%;height: 100%;" :src="flvUrl" controls></video>
      </view>
    </view>
    <view class="snap-list" v-if="activeTab == 0">
		<view v-if="snapList.length === 0" class="no-data">
			暂无数据
		</view>
		<view v-else>
			<view class="snap-item" v-for="(item,index) in snapList" :key="index">
					  <checkbox-group @change="toggleItem(item)">
						  <label class="radio" >
						    <checkbox :value="item.id" :checked="item.checked" />
						  </label>
					  </checkbox-group>
			  
			  <image :src="item.pictureUrl ? item.pictureUrl : item.url" mode=""></image>
			  <view class="desc">
			    <view class="time">
			      <text>拍摄时间:</text>
			      <text style="word-wrap: break-word;width:90%">{{formatTimestamp(item.createTime)}}</text>
			    </view>
			    <view class="pos">
			      <text>{{item.name}}</text>
			      <uni-icons type="right" size="12" style="margin-left: 8rpx;"></uni-icons>
			    </view>
			  </view>
			</view>
		</view>
	  
    </view>
    <view class="thoroughfare box">
      <text>设备通道</text>
      <view class="thoroughfare-type">
        <text>通道一</text>
        <uni-icons type="right" size="16" style="margin-left: 8rpx;color: #A1A3A5;"></uni-icons>
      </view>
    </view>
    <view class="control-box">
      <view class="control-left" @click="changeHd">
        {{isHd ? '高清' : '标清'}}
      </view>
      <div class="arrow-container">
        <uni-icons @click="cameraOperationFn(3)" class="right arrow" type="right" size="16" style="margin-left: 8rpx;" color="#DBDBDC"></uni-icons>
        <uni-icons @click="cameraOperationFn(2)" class="left arrow" type="left" size="16" style="margin-left: 8rpx;" color="#DBDBDC"></uni-icons>
        <uni-icons @click="cameraOperationFn(0)" class="top arrow" type="top" size="16" style="margin-left: 8rpx;" color="#DBDBDC"></uni-icons>
        <uni-icons @click="cameraOperationFn(1)" class="bottom arrow" type="bottom" size="16" style="margin-left: 8rpx;" color="#DBDBDC"></uni-icons>
      </div>
      <view class="control-right">
        <!-- <image :src="$getImageSrc('video-img.png')"></image> -->
      </view>
    </view>
    <view class="slider-box">
      <slider value="50" @change="sliderChange" step="10" />
    </view>
    <view class="snap-btm">
      <view class="opetion opetions" v-if="activeTab == 0">
		  <checkbox-group @change="toggleAll">
			  <label class="radio">
			    <checkbox :value="isAllSelected" :checked="isAllSelected"  /><text>全选</text>
			  </label>
		  </checkbox-group>
        <!-- <view class="export">
          导出图片地址
        </view> -->
        <view class="download" @click="downImages">
          下载原图
        </view>
      </view>
      <view class="opetion" v-if="activeTab == 1">
        <view class="view" @click="viewPopup">
          查看收藏点
        </view>
        <view class="set" @click="setPopup">
          设为收藏点
        </view>
      </view>
    </view>
    <uni-popup ref="popup" :mask-click="false" type="bottom">
      <view class="viewPopup" v-if="popType == 'view'">
        <uni-icons @click="close" class="close-icon" type="closeempty" size="25" color="#181D21"></uni-icons>
        <view class="title">
          收藏点
        </view>
        <view class="collection-points">
          <view class="collection-points-item" v-for="item in presetList" :key="item.id">
            <image :src="$getImageSrc('genbu.png')"></image>
            <view class="desc">
              {{item.pointName}}
            </view>
          </view>
        </view>
      </view>
      <view class="setPopup" v-if="popType == 'set'">
        <uni-icons @click="close" class="close-icon" type="closeempty" size="25" color="#181D21"></uni-icons>
        <view class="title">
          设为收藏点
        </view>
        <view class="form-input">
          <input type="text" placeholder="输入收藏点名称" v-model="pointName" />
        </view>
        <text>注：抓拍时间为固定每天12点</text>
        <view class="submit-btn" @click="configPresetBtn">
          确定
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { configPreset, queryPreset, moveToPreset, getChannelSnap,cameraOperation,getPresetFile,downloadById,equipmentPage } from '../../untils/api.js'
import {formatTimestamp,getStorageSync} from '../../untils/pubic.js'
import JSZip from 'jszip';
export default {
  data() {
    return {
      visibleView: true,
      date: '',
      isHd: true,
      popType: '',
      radio: true,
      activeTab: 1,
      tabsList: ['抓拍列表', '视频监控'],
      flvUrl: '',
      flvHdUrl: '',
      equipmentCode: '',
      pointName: '',
      currFlvUrl: '',
      presetList: [],
	  // 抓拍列表
      snapList: [],
	  silderValue:50,
      selectedItems: [], // 选中的项（存储 id）
	  equipmentList:[],
	  currpreset:'',
	  webviewUrl:'',
	  isVideo:true
    }
  },
  computed: {
    // 计算属性：是否全选
    isAllSelected: {
      get() {
        // 当选中项的数量等于列表项的数量时，全选
        return this.selectedItems.length === this.snapList.length;
      },
      set(value) {
		  console.log(value);
        // 根据全选状态更新 selectedItems
        if (value) {
          this.selectedItems = this.snapList.map(item => item.id);
          this.snapList.forEach(item => item.checked = true);
        } else {
          this.selectedItems = [];
          this.snapList.forEach(item => item.checked = false);
        }
      },
    },
  },
  methods: {
	  formatTimestamp,
	  getEquipmentPage() {
		  const params = {
					pageNo: 1,
					pageSize: 10,
					productType: '002'
				}
		  equipmentPage(params).then(res => {
			  this.equipmentList = res.data.list
		  })
	  },
	  async downImages() {
		  if(!this.selectedItems.length) return uni.showToast({
		  	title:'请选择图片',
			icon:'none'
		  })
		  const ids = this.selectedItems.join()
		  uni.showLoading({
		  	title:'文件加载中'
		  })
		  const res =await downloadById({ids:ids})
		  const filePath = `${wx.env.USER_DATA_PATH}/temp.zip`; // 临时文件路径
		  
			const fs = wx.getFileSystemManager();
			fs.writeFile({
			  filePath,
			  data: res,
			  encoding: 'binary', // 指定编码为 binary
			  success:() =>{
				console.log('文件保存成功', filePath);
				this.unzipAndPreviewImages(filePath); // 解压并预览图片
				uni.hideLoading()
				this.selectedItems = []
				this.isAllSelected = false
			  },
			  fail(err) {
				console.error('文件保存失败', err);
				wx.showToast({
				  title: '文件保存失败',
				  icon: 'none'
				});
				uni.hideLoading()
			  }
			});
		        
	  },
	  unzipAndPreviewImages(filePath) {
	    const fs = wx.getFileSystemManager();
	    fs.readFile({
	      filePath,
	      encoding: 'binary', // 指定编码为 binary
	      success:(res) =>{
	        const zip = new JSZip();
	        zip.loadAsync(res.data).then((contents) => {
	          const imageUrls = []; // 存储图片的临时路径
	  
	          // 遍历 ZIP 文件中的内容
	          Object.keys(contents.files).forEach((filename) => {
	            const file = contents.files[filename];
	            if (!file.dir && this.isImageFile(filename)) { // 忽略文件夹和非图片文件
	              file.async('arraybuffer').then((fileData) => {
	                // 将图片保存为临时文件
	                const imagePath = `${wx.env.USER_DATA_PATH}/${filename}`;
	                fs.writeFile({
	                  filePath: imagePath,
	                  data: fileData,
	                  encoding: 'binary',
	                  success:() =>{
	                    console.log('图片保存成功', imagePath);
	                    imageUrls.push(imagePath);
	  
	                    // 如果所有图片都已保存，预览图片
	                    if (imageUrls.length === Object.keys(contents.files).length) {
	                      this.previewImages(imageUrls);
	                    }
	                  },
	                  fail(err) {
	                    console.error('图片保存失败', err);
	                  }
	                });
	              });
	            }
	          });
	        }).catch(err => {
	          console.error('解压失败', err);
	          wx.showToast({
	            title: '解压失败',
	            icon: 'none'
	          });
	        });
	      },
	      fail(err) {
	        console.error('读取文件失败', err);
	        wx.showToast({
	          title: '读取文件失败',
	          icon: 'none'
	        });
	      }
	    });
	  },
	  // 判断文件是否为图片
	  isImageFile(filename) {
	    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
	    const ext = filename.split('.').pop().toLowerCase();
	    return imageExtensions.includes(ext);
	  },
	  
	  // 预览图片
	  previewImages(imageUrls) {
	    wx.previewImage({
	      urls: imageUrls, // 图片路径列表
	      current: imageUrls[0], // 当前显示的图片
	      success(res) {
	        console.log('图片预览成功', res);
	      },
	      fail(err) {
	        console.error('图片预览失败', err);
	      }
	    });
	  },
	  async getSnapList() {
		  this.snapList = []
		  uni.showLoading({
		  	title:'加载中'
		  })
		  const res = await getPresetFile({deviceCode:this.equipmentCode,presetCode:this.currpreset})
		  console.log(res,'ress');
		  if(res.code == 200) {
			  this.snapList = res.data.list
		  }
		  uni.hideLoading()
	  },
    toggleAll(val) {
		console.log(val);
      this.isAllSelected = !this.isAllSelected;
    },
    toggleItem(item) {
      item.checked = !item.checked;
      if (item.checked) {
        this.selectedItems.push(item.id);
      } else {
        const index = this.selectedItems.indexOf(item.id);
        if (index > -1) {
          this.selectedItems.splice(index, 1);
        }
      }
	  console.log(this.selectedItems,'selectedItems');
    },
	handerChangeEqu(val) {
		this.isVideo = false
		console.log(val);
		this.equipmentCode = this.equipmentList[val.detail.value].equipmentCode
		this.flvUrl = this.equipmentList[val.detail.value].flv
		this.isVideo = true
		this.getSnapList()
		this.queryPresetFn()
	},
    handerChangeSC(val) { 
		console.log(val);
		const item = this.presetList[val.detail.value]
		this.currpreset = item.pointCode
		this.getSnapList()
	},
    bindDateChange(val) {
      console.log(val);
    },
    // 滑块
    sliderChange(val) {
      console.log(val);
	  const type = val.detail.value >= this.silderValue ? 8 : 9
	  this.silderValue = val.detail.value
	  this.cameraOperationFn(type)
    },
    async cameraOperationFn(type) {
      try {
		  uni.showLoading({
		  	title:'加载中'
		  })
		 const data = {
			 operation:type,
			 equipmentCode:this.equipmentCode
		 }
		 const satoken  = getStorageSync('satoken') || '';
			uni.request({
			  url: 'https://iot.shunongyiqi.com/admin-api/zy/wx/ryCameraOperation',
			  method: 'POST',
			  data: data,  // 获取表单数据
			  header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Authorization' :'Bearer ' + satoken
			  },
			  success: (res) => {
				console.log('请求成功', res.data);
				uni.hideLoading()
			  },
			  fail: (err) => {
				console.error('请求失败', err);
			  }
		});

		
      } catch (error) {
		  console.log(error,'errrr');
      	//TODO handle the exception
		// uni.hideLoading()
      }
	  
    },
    changeHd() {
		return
      this.isHd = !this.isHd
      this.currFlvUrl = this.isHd ? this.flvHdUrl : this.flvUrl
    },
    async queryPresetFn() {
      const res = await queryPreset({ deviceId: this.equipmentCode })
      console.log(res, '收藏点');
	  this.presetList = res.data
    },
    async configPresetBtn() {
      const data = {
        deviceId: this.equipmentCode,
        pointName: this.pointName
      }
      const res = await configPreset(data)
	  if(res.code == 200) {
		  uni.showToast({
		  	title:'操作成功',
			icon:'none'
		  })
	  }
      this.close()
	  this.pointName = ''
    },
    viewPopup() {
      this.popType = 'view'
      this.queryPresetFn()
      this.$refs.popup.open()
    },
    setPopup() {
      this.popType = 'set'
      this.$refs.popup.open()
    },
    close() {
      this.$refs.popup.close()
    }
  },
  onLoad(options) {
	  this.getEquipmentPage()
    console.log(options);
    this.activeTab = options.type
    this.flvUrl = decodeURIComponent(options.flv)
    // this.flvHdUrl = options.flvHd
    this.equipmentCode = options.equipmentCode
	this.getSnapList()
	this.queryPresetFn()
	
	
  },
  mounted(){
	// this.webviewUrl = 'http://10.20.20.156:8081/'
	setTimeout(() => {
		// this.webviewUrl = 'http://10.20.20.156:8081/'
	}, 1000);
  }
}
</script>
<style lang="scss" scoped>
#webview{
   height: 400rpx!important;
   overflow: scroll;
}
	.no-data {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		/* 根据需要调整 */
		font-size: 16px;
		color: #999;
	}
	
	.slider-box {
		margin: 0 auto;
		width: 70%;
		margin-top: 24rpx;
	}
	.setPopup {
		box-sizing: border-box;
		position: relative;
		width: 750rpx;
		background: #fff;
		height: 460rpx;
		padding: 0 30rpx;
		padding-top: 36rpx;
		.close-icon {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
		}
		.title {
			font-weight: 500;
			text-align: center;
			font-size: 32rpx;
			color: #181B21;
			margin: 0 auto;
			margin-bottom: 36rpx;
		}
		.form-input {
			display: flex;
			align-items: center;
			width: 690rpx;
			height: 80rpx;
			background: #FFFFFF;
			border-radius: 12rpx;
			border: 1rpx solid #CACCCE;
			input {
				margin-left: 30rpx;
			}
			margin-bottom: 20rpx;
		}
		text {
			font-weight: 400;
			font-size: 24rpx;
			color: #EF6A0A;
		}
		.submit-btn {
			width: 686rpx;
			height: 90rpx;
			background: #00B23C;
			box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244,49,34,0.02);
			border-radius: 16rpx;
			margin-top: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			font-size: 32rpx;
		}
	}
	.viewPopup {
		position: relative;
		width: 750rpx;
		background: #F4F5F5;
		max-height: 1048rpx;
		padding-top: 36rpx;
		.close-icon {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
		}
		.title {
			font-weight: 500;
			text-align: center;
			font-size: 32rpx;
			color: #181B21;
			margin: 0 auto;
			margin-bottom: 36rpx;
		}
		.collection-points {
			max-height: 900rpx;
			min-height: 600rpx;
			overflow-y: auto;
			display: flex;
			flex-wrap: wrap;
			margin: 0 24rpx;
			.collection-points-item {
				margin-right: 20rpx;
				width: 336rpx;
				height: 268rpx;
				margin-bottom: 18rpx;
				background: #FFFFFF;
				border-radius: 12rpx;
				&:nth-child(even) {
					margin-right: 0;
				}
				image {
					width: 100%;
					height: 196rpx;
				}
				.desc {
					margin-left: 16rpx;
					height: 72rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #181D21;
					display: flex;
					align-items: center;

				}
			}
			
		}
	}
	.control-box {
		display: flex;
		align-items: center;
		margin-top: 70rpx;
		.control-left {
			margin: 0 60rpx 0 66rpx;
			width: 88rpx;
			height: 88rpx;
			background: #F2F2F3;
			border-radius: 50%;
			border: 1rpx solid #D8D9DA;
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: 400;
			font-size: 24rpx;
			color: #c7c8ca;
		}
		.control-right {
			margin: 0 66rpx 0 60rpx;
			width: 88rpx;
			height: 88rpx;
			background: #F2F2F3;
			border-radius: 50%;
			border: 1rpx solid #D8D9DA;
			display: flex;
			justify-content: center;
			align-items: center;
			image {
				width: 60rpx;
				height: 60rpx;
			}
		}
	}
	.video-process {
		width: 480rpx;
		height: 4rpx;
		background: #00B23C;
		border-radius: 2rpx;
		position: relative;
		margin: 0 auto;
		margin-top: 70rpx;
		&::after {
			position: absolute;
			left: 50%;
			top: -16rpx;
			content: '';
			height: 32rpx;
			width: 32rpx;
			border-radius: 50%;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 24rpx 0rpx rgba(0,178,60,0.3);
		}
	}
	/* 创建一个圆形按钮容器 */
	.arrow-container {
		width: 320rpx;
		height: 320rpx;
		border-radius: 50%;
		background-color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	/* 中间的圆形高亮区域 */
	.arrow-container::before {
		content: "";
		width: 128rpx;
		height: 128rpx;
		border-radius: 50%;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 32rpx 0rpx rgba(0, 178, 60, 0.3);
		position: absolute;
	}

	.arrow {
		position: absolute;
	}

	.right {
		right: 24rpx;
	}

	.left {
		left: 24rpx;
	}

	.top {
		top: 24rpx;
	}

	.bottom {
		bottom: 24rpx;
	}

	.snap-container {
		height: 100%;
		background: #F4F5F5;
		overflow: hidden;

		.equi-id {
			width: 750rpx;
			height: 178rpx;
			overflow: hidden;
			background: #FFFFFF;

			.tabs-top {
				margin: 30rpx 24rpx 30rpx 30rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.video {
					width: 750rpx;
					height: 422rpx;
					background-color: #fff;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.tabs {
				display: flex;
				align-items: center;
				height: 20px;
			}

			.tabs-item {
				width: 60px;
				height: 15px;
				font-weight: 500;
				font-size: 15px;
				color: #535557;
				line-height: 15px;
				margin-right: 16px;
			}

			.activeTab {
				position: relative;
				color: #00B23C;

				&::after {
					position: absolute;
					bottom: -4px;
					left: 0;
					content: '';
					width: 59px;
					height: 2px;
					background: #00B23C;
					border-radius: 2px 2px 2px 2px;
				}
			}

			.id {
				font-weight: 500;
				font-size: 28rpx;
				color: #181D21;
			}

			.filter {
				display: flex;
				font-weight: 400;
				font-size: 26rpx;
				color: #535457;
				margin: 38rpx 0 0 24rpx;

				.filter-item {
					box-sizing: border-box;
					padding: 0 24rpx;
					height: 50rpx;
					background: #F4F5F5;
					border-radius: 8rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 24rpx;
				}
			}
		}

		.snap-list {
			margin: 0 24rpx;
			height: 1052rpx;
			overflow: hidden;
			overflow-y: auto;

			.snap-item {
				display: flex;
				align-items: center;
				margin-top: 18rpx;
				width: 710rpx;
				height: 228rpx;
				background: #FFFFFF;
				border-radius: 16rpx;

				.radio {
					margin: 0 24rpx;
				}

				image {
					width: 320rpx;
					height: 180rpx;
				}

				.desc {
					height: 180rpx;
					margin-left: 24rpx;
					font-weight: 400;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.time {
						font-size: 28rpx;
						color: #A1A3A5;
						display: flex;
						flex-direction: column;
					}

					.pos {
						font-size: 28rpx;
						color: #181B21;
					}
				}
			}
		}

		.snap-btm {
			position: fixed;
			bottom: 0;
			width: 750rpx;
			height: 198rpx;
			background: #FFFFFF;
			.opetions {
				justify-content: space-between;
			}
			.opetion {
				margin: 0 24rpx;
				height: 130rpx;
				display: flex;
				align-items: center;

				.radio {
					height: 40rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #000000;
				}

				.export {
					width: 276rpx;
					height: 90rpx;
					background: #FFFFFF;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					border: 1rpx solid #CACCCE;
					margin: 0 20rpx 0 72rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.download {
					display: flex;
					align-items: center;
					color: #fff;
					justify-content: center;
					width: 210rpx;
					height: 90rpx;
					background: #00B23C;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
				}
				.view {
					width: 334rpx;
					height: 90rpx;
					background: #FFFFFF;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					border: 1rpx solid #CACCCE;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 24rpx;
				}
				
				.set {
					width: 334rpx;
					display: flex;
					align-items: center;
					color: #fff;
					justify-content: center;
					height: 90rpx;
					background: #00B23C;
					box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(244, 49, 34, 0.02);
					border-radius: 16rpx 16rpx 16rpx 16rpx;
				}
			}
		}

		.thoroughfare {
			margin-top: 20rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
			height: 112rpx;
			display: flex;
			font-weight: 500;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			color: #181B21;

			.thoroughfare-type {
				font-weight: 400;
				color: #181B21;
				display: flex;
				align-items: center;
			}
		}
	}
</style>